package logic

import (
	"context"
	"fmt"
	"product-mall/models/cache"
	"product-mall/models/mysql"
	"product-mall/pkg"

	"product-mall/productrpc/internal/svc"
	"product-mall/productrpc/productrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RegisterLogic) Register(in *productrpc.RegisterRequest) (*productrpc.RegisterResponse, error) {
	// todo: add your logic here and delete this line

	get := cache.Rdb.Get(l.ctx, "sendSms"+"register"+in.Mobile)
	if get.Val() != in.CaptSms {
		return nil, fmt.Errorf("短信验证码错误,请重新输入")
	}

	var Find mysql.User
	mysql.DB.Debug().Where("account = ?", in.Mobile).Find(&Find)
	if Find.ID != 0 {
		return nil, fmt.Errorf("账号已注册,请前往登录")
	}

	var user mysql.User

	if in.Password != "" {
		user = mysql.User{
			Account:  in.Mobile,
			Password: pkg.Md5(in.Password),
		}
	} else {
		user = mysql.User{
			Account:  in.Mobile,
			Password: pkg.Md5(in.Mobile),
		}
	}

	err := mysql.DB.Debug().Create(&user).Error
	if err != nil {
		return nil, fmt.Errorf("注册失败")
	}

	//成功后清除短信验证码缓存
	cache.Rdb.Del(l.ctx, "sendSms"+"register"+in.Mobile)
	return &productrpc.RegisterResponse{UserId: int64(user.ID)}, nil
}
